import { createRouter, createWebHistory } from 'vue-router'
import {useUserStore} from '@/stores'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {path:'/login',component:()=>import('@/views/login/LoginPage.vue')},
    {
      path:'/',
      component:()=>import('@/views/Layout/LayoutContainer.vue'),
      redirect:'/user/userShow',
      children:[
       { path:'/user/userShow',component:()=>import('@/views/user/userShow.vue')},
       { path:'/user/follow',component:()=>import('@/views/user/userFollow.vue')},
       {path:'/user/articles',component:()=>import('@/views/user/userArticles.vue')},
      ]
    },
  ],
})

router.beforeEach((to) => {
  const userStore = useUserStore()
  
  // 登录页面特殊处理
  if (to.path === '/login') {
    // 如果已经有token，跳转到首页
    if (userStore.token || sessionStorage.getItem('access_token')) {
      return '/'
    }
    return true
  }
  
  // 非登录页面，检查是否有token（access_token或refresh_token）
  const hasAccessToken = userStore.token || sessionStorage.getItem('access_token')
  const hasRefreshToken = localStorage.getItem('refresh_token') || sessionStorage.getItem('refresh_token')
  
  // 既没有access_token也没有refresh_token，跳转到登录
  if (!hasAccessToken && !hasRefreshToken) {
    return '/login'
  }
  
  // 有refresh_token但没有access_token，允许进入
  // 具体的token刷新由axios拦截器处理
  // 如果refresh_token也过期了，axios拦截器会跳转到登录页
  return true
})

export default router